package com.example.mybaitsplusdemo.service;

import com.example.mybaitsplusdemo.bo.CustomUserDetails;
import com.example.mybaitsplusdemo.entity.Users;
import com.example.mybaitsplusdemo.entity.authorities;
import com.example.mybaitsplusdemo.mapper.AuthoritiesMapper;
import com.example.mybaitsplusdemo.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private AuthoritiesMapper authoritiesMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users=usersMapper.selectById(username);
        if(users==null)
            throw new UsernameNotFoundException("用户名不存在");

        //查找当前用户名对应的权限列表
        Map<String, Object> map = new HashMap<>();
        map.put("username", users.getUsername());
        List<authorities> authoritiesList = authoritiesMapper.selectByMap(map);

        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        for(authorities authorities:authoritiesList){
            auths.add(new SimpleGrantedAuthority(authorities.getAuthority()));
        }

        CustomUserDetails customUserDetails= new CustomUserDetails(users,auths);
        return  customUserDetails;

    }
}
